package com.forum.controller;

import com.forum.common.JwtUtils;
import com.forum.entity.Result;
import com.forum.entity.User;
import com.forum.service.LoginService;
import com.forum.util.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping
@Api(tags = "登录注册")
public class LoginController {

    @Resource
    LoginService loginService;

    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public ResponseEntity<Result> login(@RequestBody User user) {
        log.info("登录：{}", user);
//        String password = MD5Utils.inputPassToFormPass(user.getPassword());
        User u = loginService.login(user.getAccount(), user.getPassword());
        log.info("查询到的用户:{}", u);
        if (u != null) {
            Map<String, Object> claims = new HashMap<>();
            //创建一个jwt令牌存储对象
            claims.put("id", u.getId());
            claims.put("account", u.getAccount());
            claims.put("password", u.getPassword());
            String jwt = JwtUtils.generateJwt(claims);
            return ResponseEntity.ok(Result.ok("登录成功", jwt));
        }
        return ResponseEntity.badRequest().body(Result.fail("账号或密码错误"));
    }

    @PostMapping("/regedit")
    @ApiOperation(value = "注册")
    public Result<User> regedit(@RequestBody User user) {
        log.info("注册：{}", user);
        return loginService.regedit(user);
    }
}
